<template>
  <div class="api-history">
    <div class="history-l">
      <div class="filtered">
        <div class="filtered-top">
          <div class="title">{{ $t('module.apiManage.filterCriteria') }}</div>
          <div @click="openDrawer" v-if="isSearch" class="filtered-btn">
            查看条件
            <Icon type="md-arrow-dropdown" class="filtered-icon" />
          </div>
          <div @click="openDrawer" v-else class="filtered-btn">
            全部
            <Icon type="md-arrow-dropdown" class="filtered-icon" />
          </div>
        </div>
        <!-- <div class="filtered-item-box" v-if="false">
          <div class="search-item-wrap" v-for="(value, key) in searchForm" :key="key" v-show="value !== '' && value !== null && key !== 'datePicker'">
            <div class="item-label">{{ searchMap[key] }}：</div>
            <div class="item-value">{{ value }}</div>
            <Icon type="ios-close" class="close-btn" />
          </div>
        </div> -->
      </div>
      <ul class="history-list-wrap">
        <li v-show="historyList.length < 1" class="is-empty">暂无数据</li>
        <li
          :class="{ 'is-active': currentHistoryInfo.id === item.id }"
          @click="onDetail(item)"
          v-for="item in historyList"
          :key="item.id"
        >
          <div class="path">{{ item.requestUrl }}</div>
          <div class="other">
            <div class="other-l">
              <div class="req-type">{{ item.requestMethod }}</div>
              <div class="req-state">{{ item.statusCode }}</div>
            </div>
            <div class="time-consuming">{{ item.consumptionTime }}ms</div>
          </div>
          <div class="req-time">{{ item.requestTime }}</div>
        </li>
      </ul>
    </div>
    <div class="history-r">
      <div class="top-bar">
        <div class="title">{{ currentHistoryInfo.requestUrl }}</div>
        <div class="operate-bar">
          <div @click="onExpandAll(false)" v-if="isExpandAll">
            <Tooltip :content="$t('module.apiManage.retractAll')" transfer placement="top">
              <embed
                :src="require('../../../asset/images/icon_quanbushouqi.svg')"
                width="26"
                height="26"
                type="image/svg+xml"
                class="node-svg"
              />
            </Tooltip>
          </div>
          <div @click="onExpandAll(true)" v-if="!isExpandAll">
            <Tooltip :content="$t('module.apiManage.expandAll')" transfer placement="top">
              <embed
                :src="require('../../../asset/images/icon_quanbuzhankai.svg')"
                width="26"
                height="26"
                type="image/svg+xml"
                class="node-svg"
              />
            </Tooltip>
          </div>
        </div>
      </div>
      <div class="history-detail-wrap">
        <Collapse v-model="expandList" @on-change="expandChange" simple class="custom-collapse">
          <Panel name="1">
            基本信息
            <template #content>
              <div class="info-content" v-if="historyList.length < 1">暂无数据</div>
              <div class="info-content" v-else>
                <div class="item-wrap">
                  <div class="item-label">Request URL</div>
                  <div class="item-value">{{ currentHistoryInfo.requestUrl }}</div>
                </div>
                <div class="item-wrap">
                  <div class="item-label">Request Method</div>
                  <div class="item-value">{{ currentHistoryInfo.requestMethod }}</div>
                </div>
                <div class="item-wrap">
                  <div class="item-label">Status Code</div>
                  <div class="item-value">
                    <span
                      class="status-radius"
                      :class="{
                        'color-l': currentHistoryInfo.statusCode != 200 && currentHistoryInfo.statusCode < 400,
                        'color-s': currentHistoryInfo.statusCode == 200,
                        'color-r': currentHistoryInfo.statusCode > 399
                      }"
                    >
                    </span>
                    {{ currentHistoryInfo.statusCode }}
                    <span v-show="currentHistoryInfo.statusCode == 200">OK</span>
                  </div>
                </div>
                <div class="item-wrap">
                  <div class="item-label">Remote Address</div>
                  <div class="item-value">{{ currentHistoryInfo.remoteAddress }}</div>
                </div>
                <div class="item-wrap">
                  <div class="item-label">Referrer Policy</div>
                  <div class="item-value">{{ currentHistoryInfo.referrerPolicy }}</div>
                </div>
              </div>
            </template>
          </Panel>
          <Panel name="2">
            请求头
            <template #content>
              <div class="info-content" v-if="historyList.length < 1 || !currentHistoryInfo.requestHeaders">暂无数据</div>
              <div class="info-content" v-else>
                <div class="item-wrap" v-for="(value, key) in currentHistoryInfo.requestHeaders" :key="key">
                  <div class="item-label">{{ key }}</div>
                  <div class="item-value">{{ value }}</div>
                </div>
              </div>
            </template>
          </Panel>
          <Panel name="3">
            响应头
            <template #content>
              <div class="info-content" v-if="historyList.length < 1 || !currentHistoryInfo.responseHeaders">暂无数据</div>
              <div class="info-content" v-else>
                <div class="item-wrap" v-for="(value, key) in currentHistoryInfo.responseHeaders" :key="key">
                  <div class="item-label">{{ key }}</div>
                  <div class="item-value">{{ value }}</div>
                </div>
              </div>
            </template>
          </Panel>
          <Panel name="4">
            响应体
            <template #content>
              <div class="info-content" v-if="historyList.length < 1 || !currentHistoryInfo.responseData">暂无数据</div>

              <div class="info-content" style="height: 260px" v-else>
                <code-editor
                  ref="codeEditor"
                  :config="editorConfig"
                  v-model="currentHistoryInfo.responseData"
                ></code-editor>
                <!-- <div class="item-wrap" v-for="(value, key) in currentHistoryInfo.responseData" :key="key">
                  <div class="item-label">{{ key }}</div>
                  <div class="item-value">{{ value }}</div>
                </div> -->
              </div>
            </template>
          </Panel>
        </Collapse>
      </div>
    </div>

    <Drawer
      class="searchDrawer"
      class-name="searchDrawer-content"
      width="372"
      placement="left"
      inner
      :transfer="false"
      :title="$t('module.apiManage.screen')"
      @on-close="closeDrawer"
      v-model="isDrawer"
    >
    <div class="searchForm">
      <Form :model="searchForm" ref="searchForm" label-position="top">
        <Form-item prop="requestUrl" label="请求地址">
          <Input :placeholder="$t('common.pleaseInput')" v-model.trim="searchForm.requestUrl" :maxlength="32"></Input>
        </Form-item>
        <Form-item prop="remoteAddress" label="客户端地址">
          <Input
            :placeholder="$t('common.pleaseInput')"
            v-model.trim="searchForm.remoteAddress"
            :maxlength="32"
          ></Input>
        </Form-item>
        <Form-item prop="statusCode" label="状态码">
          <!-- <Input :placeholder="$t('common.pleaseInput')" v-model.trim="searchForm.statusCode" type="number"></Input> -->
          <InputNumber
            :max="1000"
            :step="1"
            :precision="0"
            :placeholder="$t('common.pleaseInput')"
            v-model="searchForm.statusCode"
            style="width: 100%"
          ></InputNumber>
        </Form-item>
        <Form-item prop="consumptionTimeStart" label="耗时范围">
          <div class="consumptionTime">
            <InputNumber
              :step="1"
              :precision="0"
              :placeholder="$t('common.pleaseInput')"
              v-model="searchForm.consumptionTimeStart"
              style="width: 100%"
            ></InputNumber>
            -
            <InputNumber
              :step="1"
              :precision="0"
              :placeholder="$t('common.pleaseInput')"
              v-model="searchForm.consumptionTimeEnd"
              style="width: 100%"
            ></InputNumber>
          </div>
        </Form-item>
        <Form-item prop="datePicker" label="时间范围">
          <DatePicker
            v-model="searchForm.datePicker"
            @on-change="datePickerChange"
            type="datetimerange"
            transfer
            format="yyyy-MM-dd HH:mm:ss"
            :placeholder="$t('common.pleaseSelect')"
            style="width: 100%"
          />
        </Form-item>
      </Form>
    </div>

      <div class="operate-bar">
        <RPButton optType="create" text="确定" @click="onSearch" />
        <RPButton optType="reset" @click="onReset" />
      </div>
    </Drawer>
  </div>
</template>
<script>
import { getApiHistoryList, getHistoryDetail } from '@/api/apiManagement.js'
import codeEditor from '@/components/common/CodeEditor/index.vue'
export default {
  name: 'apiHistory',
  props: {
    detailInfo: {
      type: Object,
      default: {}
    }
  },
  components: {
    codeEditor
  },
  data() {
    return {
      expandList: ['1'],
      isDrawer: false,
      searchForm: {
        requestUrl: '', // 请求地址
        remoteAddress: '', // 客户端地址
        statusCode: null, // 状态码
        consumptionTimeStart: null, // 耗时时间开始
        consumptionTimeEnd: null, // 耗时时间结束
        requestTimeStart: '', // 请求时间开始
        requestTimeEnd: '', // 请求时间结束
        datePicker: []
      },
      searchMap: {
        requestUrl: '请求地址',
        remoteAddress: '客户端地址',
        statusCode: '状态码',
        consumptionTimeStart: ''
      },
      historyList: [],
      currentHistoryInfo: {},
      firstSearchKey: '',
      editorConfig: {
        readOnly: true,
        language: 'json',
        theme: 'vs',
        lineNumbers: false,
        fontSize: 14,
      }
    }
  },
  created() {
    
    const nowDate = new Date().Format("yyyy-MM-dd")
    const startTime = `${nowDate} 00:00:00`
    const endTime = `${nowDate} 23:59:59`
    this.searchForm.requestTimeStart = startTime
    this.searchForm.requestTimeEnd = endTime
    this.searchForm.datePicker = [startTime, endTime]
    this.getApiHistory()
  },
  computed: {
    isExpandAll() {
      return this.expandList.length === 4
    },
    isSearch() {
      for (const key in this.searchForm) {
        if (Object.hasOwnProperty.call(this.searchForm, key)) {
          const element = this.searchForm[key]
          if (element !== '' && element !== null && key !== 'datePicker') {
            this.firstSearchKey = key
            return true
          }
        }
      }
      this.firstSearchKey = ''
      return false
    }
  },
  methods: {
    expandChange(val) {},
    onExpandAll(val) {
      if (val) {
        this.expandList = ['1', '2', '3', '4']
      } else {
        this.expandList = []
      }
    },
    closeDrawer(isCustom) {
      this.searchForm = Object.assign({}, this.searchFormOld)
    },
    openDrawer() {
      this.searchFormOld = Object.assign({}, this.searchForm)
      this.isDrawer = true
    },
    datePickerChange(val) {
      if (val[0]) {
        this.searchForm.requestTimeStart = val[0]
        this.searchForm.requestTimeEnd = val[1]
      }
    },
    onReset() {
      this.searchForm.requestUrl = ''
      this.searchForm.remoteAddress = ''
      this.searchForm.statusCode = null
      this.searchForm.consumptionTimeStart = null
      this.searchForm.consumptionTimeEnd = null
      this.searchForm.requestTimeStart = ''
      this.searchForm.requestTimeEnd = ''
      this.searchForm.datePicker = []
    },
    onSearch() {
      this.getApiHistory()
      this.isDrawer = false
    },
    // 获取历史记录
    getApiHistory() {
      const paramObj = Object.assign({}, this.searchForm, {
        apiId: this.detailInfo.apiPath ? this.detailInfo.id : '',
        resource: this.detailInfo.resource, // 接口地址/api路径
        routeId: this.detailInfo.routeId, // 分组对应的路由id
        tenantCode: this.detailInfo.tenantCode
      })
      getApiHistoryList(paramObj).then(res => {
        this.historyList = res.data
        if (res.data.length) {
          this.onDetail(res.data[0])
        } else {
          this.currentHistoryInfo = {}
        }
      })
    },
    onDetail(val) {
      const info = val
      const _this = this
      try {
        info.requestHeaders = JSON.parse(val.requestHeaders)
        info.responseHeaders = JSON.parse(val.responseHeaders)
        // info.responseData = JSON.parse(val.responseData)
      } catch (error) {}
      this.currentHistoryInfo = info
      this.$nextTick(() => {
        _this.$refs.codeEditor && _this.$refs.codeEditor.setValue(this.checkJsonCode(this.currentHistoryInfo.responseData))
      })
    },
    checkJsonCode(strJsonCode) {
      let res = ''
      try {
        for (let i = 0, j = 0, k = 0, ii, ele; i < strJsonCode.length; i++) {
          ele = strJsonCode.charAt(i)
          if (j % 2 === 0 && ele === '}') {
            // eslint-disable-next-line no-plusplus
            k--
            for (ii = 0; ii < k; ii++) ele = `    ${ele}`
            ele = `\n${ele}`
          } else if (j % 2 === 0 && ele === '{') {
            ele += '\n'
            // eslint-disable-next-line no-plusplus
            k++
            for (ii = 0; ii < k; ii++) ele += '   '
          } else if (j % 2 === 0 && ele === ',') {
            ele += '\n'
            for (ii = 0; ii < k; ii++) ele += '  '
            // eslint-disable-next-line no-plusplus
          } else if (ele === '"') j++
          res += ele
        }
      } catch (error) {
        res = strJsonCode
      }
      return res
    }
  }
}
</script>
<style lang="less">
.api-management-detail {
  &:has(.api-history) {
    .header-bar {
      margin-bottom: 0 !important;
    }
  }
}
</style>
<style lang="less" scoped>
.node-svg {
  position: relative;
  top: 1px;
  border: 1px solid #e2e4ea;
  &:hover {
    background-color: #e8ecef;
  }
}
.api-history {
  position: relative;
  display: flex;
  height: calc(100% - 56px);
  .searchDrawer {
    /deep/.ivu-drawer-mask {
      background-color: transparent;
    }
    /deep/.searchDrawer-content {
      .ivu-drawer {
        .ivu-drawer-content {
          .ivu-drawer-close {
            .ivu-icon {
              font-size: 24px;
            }
          }
          .ivu-drawer-header {
            padding: 12px;
          }
          .ivu-drawer-body {
            position: relative;
            padding: 0px;
            height: calc(100% - 46px);
            .ivu-form {
              .ivu-form-item {
                .ivu-form-item-label {
                  font-size: 14px;
                  color: #333333;
                  letter-spacing: 0;
                  margin-bottom: 10px;
                  line-height: 30px;
                  display: inline;
                }
                .consumptionTime {
                  display: flex;
                }
              }
            }
            .operate-bar {
              position: absolute;
              width: 100%;
              bottom: 0;
              left: 0;
              padding: 10px 22px;
              text-align: right;
              button {
                &:last-child {
                  margin-left: 14px;
                }
              }
            }
          }
        }
      }
    }
  }
  .searchForm {
    height: calc(100% - 52px);
    padding: 12px;
    overflow-y: auto;
  }
  .history-l {
    position: relative;
    width: 232px;
    min-width: 232px;
    overflow: hidden;
    &::after {
      content: '';
      position: absolute;
      right: 0;
      top: 16px;
      height: 100%;
      width: 1px;
      background-color: #e2e4ea;
    }
    .filtered {
      //   display: flex;
      //   align-items: center;
      padding-right: 10px;
      .filtered-top {
        display: flex;
        height: 46px;
        align-items: center;
        > .filtered-btn {
          cursor: pointer;
          .filtered-icon {
            font-size: 20px;
          }
        }
      }
      .title {
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #858b9c;
        letter-spacing: 0;
        font-weight: 400;
        margin-right: 12px;
      }
      .filtered-item-box {
        // cursor: pointer;
        height: 100px;
        border: 1px solid #ccc;
        padding: 10px;
        overflow-y: auto;
      }
    }
    .history-list-wrap {
      height: calc(100% - 46px);
      overflow-y: auto;
      li {
        font-family: PingFangSC-Regular;
        height: 90px;
        padding: 12px;
        cursor: pointer;
        margin-bottom: 2px;
        .path {
          font-family: PingFangSC-Medium;
          font-size: 14px;
          color: #12151b;
          letter-spacing: 0;
          font-weight: 500;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-bottom: 8px;
        }
        .other {
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          color: #666f83;
          letter-spacing: 0;
          font-weight: 400;
          margin-bottom: 4px;
          .other-l {
            display: flex;
            align-items: center;
            .req-type {
              margin-right: 12px;
            }
          }
        }
        .req-time {
          font-size: 12px;
          color: #a3aabe;
          letter-spacing: 0;
          font-weight: 400;
        }
        &.is-active {
          background: #fff5f2;
          .path {
            color: var(--primary-color);
          }
        }
        &.is-empty {
          color: #909399;
          text-align: center;
          line-height: 90px;
        }
      }
    }
    .search-item-wrap {
      position: relative;
      display: flex;
      border: 1px solid #ccc;
      padding: 0 4px;
      padding-right: 20px;
      font-size: 12px;
      .close-btn {
        position: absolute;
        right: 2px;
        font-size: 14px;
        top: 50%;
        transform: translate(0, -50%);
      }
    }
  }
  .history-r {
    flex: 1;
    padding-left: 20px;
    .top-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 46px;
      .title {
        font-family: PingFangSC-Medium;
        font-size: 16px;
        color: #12151b;
        letter-spacing: 0;
        font-weight: 500;
      }
      .operate-bar {
        font-size: 26px;
        > div {
          display: flex;
          cursor: pointer;

          embed {
            pointer-events: none;
          }
          &:hover {
            embed {
              background-color: #e8ecef;
            }
          }
        }
      }
    }
    .history-detail-wrap {
      overflow-y: auto;
      height: calc(100% - 46px);
    }
    .custom-collapse {
      &.ivu-collapse {
        border: none;
        .ivu-collapse-item {
          border: 1px solid #e2e4ea;
          margin-bottom: 16px;
          /deep/.ivu-collapse-header {
            position: relative;
            background: #f5f7fa;
            font-family: PingFangSC-Medium;
            height: 50px;
            line-height: 50px;
            font-size: 14px;
            color: #12151b;
            letter-spacing: 0;
            font-weight: 500;
            &::before {
              content: '';
              position: absolute;
              width: 3px;
              height: 36px;
              left: 0;
              top: 7px;
              background-color: #4d84ff;
            }
            .ivu-icon {
              color: #a7adc1;
              font-size: 14px;
              margin-right: 12px;
            }
          }
          &.ivu-collapse-item-active {
            /deep/.ivu-collapse-header {
              border-color: #e2e4ea;
            }
          }
        }
      }
      /deep/.ivu-collapse-content {
        padding: 0;
        .ivu-collapse-content-box {
          padding: 0;
        }
      }
      .info-content {
        padding: 10px 20px;
        min-height: 52px;
        .item-wrap {
          display: flex;
          line-height: 32px;
          word-spacing: normal;
          .item-label {
            width: 178px;
            color: #131c36;
          }
          .item-value {
            flex: 1;
            word-break: break-all;
            font-family: PingFangSC-Regular;
            font-size: 14px;
            color: #41485d;
            letter-spacing: 0;
            font-weight: 400;
            .status-radius {
              display: inline-block;
              width: 12px;
              height: 12px;
              border-radius: 50%;
              &.color-l {
                background-color: #f78742;
              }
              &.color-s {
                background-color: #25ca79;
              }
              &.color-r {
                background-color: #ec4547;
              }
            }
          }
        }
      }
    }
  }
}
</style>